package cc.laop.netty.client;

import cc.laop.netty.entity.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyClientHandler extends SimpleChannelInboundHandler<BaseMsg> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseMsg msg)
            throws Exception {
        MsgType msgType = msg.getMsgType();
        switch (msgType) {
            case LOGIN:
                // 向服务器发起登录
                LoginMsg loginMsg = new LoginMsg();
                loginMsg.setUserid("101");
                loginMsg.setChannelid(Constants.channelid.get());
                ctx.writeAndFlush(loginMsg);
                break;
            case PING:
                System.out.println(Thread.currentThread().getName()
                        + ": receive ping from server: " + msg.getChannelid());
                break;
            case ASK:
                AskMsg am = (AskMsg) msg;
                System.out.println(Thread.currentThread().getName()
                        + ": receive ask from server: " + am.getMessage());
                ReplyMsg replyMsg = new ReplyMsg();
                replyMsg.setMessage("reply");
                replyMsg.setChannelid(Constants.channelid.get());
                ctx.writeAndFlush(replyMsg);
                break;
            case REPLY:
                ReplyMsg rm = (ReplyMsg) msg;
                System.out.println(Thread.currentThread().getName()
                        + ": receive client msg: " + rm.getMessage());
                break;
            default:
                break;
        }

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case ALL_IDLE:
                    PingMsg pingMsg = new PingMsg();
                    pingMsg.setChannelid(Constants.channelid.get());
                    ctx.writeAndFlush(pingMsg);
                    System.out.println(Thread.currentThread().getName()
                            + ": Send ping to server: "
                            + Constants.channelid.get());
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
